package com.scalar.chiptrack.operations.packingslip.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.commons.Location;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.SearchPackingSlipForm;
import com.scalar.chiptrack.operations.packingslip.PackingSlip;
import com.scalar.chiptrack.operations.vendor.Vendor;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Calendar;

/**
 * User: Sujan
 * Date: Jan 3, 2007
 * Time: 12:24:06 PM
 */
public class ExtUserSearchPackingSlipAction extends ChipTrackAction
{
    public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
	{
		HttpSession session = request.getSession();
		User user 			= (User) session.getAttribute ( SessionKeys.USER_KEY );
		HashMap errors 		= new HashMap();
		HashMap info 		= new HashMap();
		String action 		= request.getParameter( "action" );
		if ( user == null )
		{
			session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/extUserSearchPackingSlip.do?" + request.getQueryString() );
			return ( mapping.findForward( "login" ) );
		}

		if ( action == null )
		{
			action = "";
		}

		if( request.getAttribute( SessionKeys.INFO_MESSAGES ) != null )
		{
			info.putAll( ( HashMap ) request.getAttribute( SessionKeys.INFO_MESSAGES ) );
		}

		if( request.getAttribute( SessionKeys.ERROR_MESSAGES ) != null )
		{
			errors.putAll( ( HashMap ) request.getAttribute( SessionKeys.ERROR_MESSAGES ) );
		}
		SearchPackingSlipForm searchForm = (SearchPackingSlipForm) form;
        request.setAttribute( SessionKeys.INFO_MESSAGES, info );
		request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
		request.setAttribute( "yearList", getYearList() );

        if( "Search".equalsIgnoreCase( action ) )
		{
			// Fetch the list for the search creteria
            searchForm.setLocation("null");
            searchForm.setCustomerId(0);
            searchForm.setManufacturingPartNo(0);
            int fgLocationAddressId = -1;
            Vendor vendor = null;
            try
            {
                vendor = VendorDAO.getVendorDetails(user.getVendorId());
            }
            catch( ScalarException e )
            {
                errors.put ( "Could not get Vendor details", null );
                return ( mapping.findForward ( "success" ) );
            }
            ArrayList locations = vendor.getLocationsList();
            int locationsListSize = locations != null ? locations.size() : 0;
            Location fgLocation = null;
            if ( locationsListSize > 0 )
            {
                fgLocation = (Location)locations.get(0);
                fgLocationAddressId = fgLocation.getAddressId();
            }
            searchForm.setAddressID(fgLocationAddressId);
            if ( fgLocationAddressId <= 0 )
            {
                errors.put ( "Vendor Finished Goods Location could not found", null );
            }
            else
            {
                ArrayList list = null;
                try
                {

                    Calendar cal = Calendar.getInstance();
                    cal.add ( Calendar.DATE, ConfigManager.getGeneratePSScheduledUptoDays() );
                    String scheduledBefore = StringUtils.formatDateToString( cal.getTime() );
                    
                    if( !ConfigManager.isVendorGeneratePackingSlip() )
                    {
                    	scheduledBefore = "01/01/1900";
                    }

                    cal = Calendar.getInstance();
                    cal.add ( Calendar.DATE, -ConfigManager.getPSShippedInDays() );
                    String shippedAfter = StringUtils.formatDateToString( cal.getTime() );
                    list = NewPackingSlipDAO.loadAllPackingSlipsForSearch( searchForm, scheduledBefore, shippedAfter );
                }
                catch ( ScalarException e )
                {
                    errors.put ( "Could not fetch Packing Slip(s)", null );
                    return ( mapping.findForward ( "success" ) );
                }
                int listSize = list != null ? list.size() : 0;
                for ( int i = 0; i < listSize; i++ )
                {
                    PackingSlip packingSlip = (PackingSlip)list.get(i);
                    if ( "OPEN".equalsIgnoreCase( packingSlip.getStatus() ) )
                    {
                        packingSlip.setLocation(fgLocation.getVendorName() + "/" + (fgLocation.getLocationAddress().getCity() == null ? "" : fgLocation.getLocationAddress().getCity()) );
                        packingSlip.setLocationAddressId ( fgLocationAddressId );
                    }
                }
                if ( list.isEmpty() == false )
                {
                    request.setAttribute( "searchList", list );
                }
                else
                {
                    errors.put( ERROR_PACKING_SLIP_NOT_FOUND, null );
                }
            }
        }

		return ( mapping.findForward ( "success" ) );
	}

    private ArrayList getYearList()
    {
		int year = 2000;
		ArrayList yearList = new ArrayList();
		for ( int i = 0; i <= 15; i++)
		{
			yearList.add( new LabelValueBean( year+"", year+"" ) );
			year++;
		}
        return yearList;
    }
}
